package com.shenyuan.superapp.base.base.mvvm;

import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.activity.ComponentActivity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.launcher.ARouter;
import com.shenyuan.superapp.base.R;
import com.shenyuan.superapp.base.utils.LogUtils;
import com.shenyuan.superapp.base.widget.GifLoadingView;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author ch
 * @date 2022/6/7-17:43
 * desc
 */
public abstract class BaseVMFragment<B extends ViewDataBinding, VM extends BaseViewModel> extends Fragment {

    /**
     * context
     */
    public Context context;

    private View rootView;

    /**
     * 当前fragment是否加载过数据,如加载过数据，则不再加载
     */
    private boolean isLoadData;

    /**
     * binding
     */
    public B binding;

    /**
     * viewModel
     */
    public VM viewModel;

    /**
     *
     */
    private ViewModelProvider viewModelProvider;

    /**
     * loading
     */
    private GifLoadingView loadingView;

    /**
     * 创建viewModel
     *
     * @return VM
     */
    protected abstract VM createViewModel();


    /**
     * 懒加载,强制子类重写
     */
    protected abstract void loadData();

    /**
     * 初始化view
     */
    protected abstract void initView();

    /**
     * 添加监听
     */
    protected abstract void addListener();


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = getBinding(inflater, container);
        if (binding != null) {
            rootView = binding.getRoot();
        }
        viewModel = createViewModel();
        initView();
        addListener();
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isLoadData) {
            isLoadData = true;
            loadData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isLoadData = false;
    }

    protected <T extends ViewModel> T getScopeViewModel(@NonNull Class<T> modelClass) {
        if (viewModelProvider == null) {
            if (getActivity() != null) {
                viewModelProvider = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication()));
            } else {
                viewModelProvider = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory());
            }
        }
        return viewModelProvider.get(modelClass);
    }


    protected <T> boolean isSucc(@NonNull BaseResult<T> result) {
        LogUtils.e("code=" + result.getCode() + ",msg=" + result.getMsg());

        if (BaseResult.CODE_SHOW_LODING.equals(result.getCode())) {
            //显示加载动画
            showLoadingDialog();
            return false;
        } else if (!BaseResult.CODE_SUCC.equals(result.getCode())) {
            closeLoadingDialog();
            showToast(result.getMsg());
            return false;
        }
        closeLoadingDialog();
        return true;
    }

    protected void closeLoadingDialog() {
        if (loadingView != null) {
            loadingView.onDismiss(null);
        }
    }


    protected void showLoadingDialog() {
        if (loadingView == null) {
            loadingView = new GifLoadingView();
            loadingView.setImageResource(R.mipmap.num19);
        }
        if (getActivity() != null) {
            loadingView.show(getActivity().getSupportFragmentManager());
        }
    }


    /**
     * @param s s
     */
    public void showToast(@NonNull String s) {
        Toast toast = Toast.makeText(context, s, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 反射获取 ViewDataBinding
     *
     * @return ViewDataBinding
     */
    private B getBinding(LayoutInflater inflater, ViewGroup container) {
        if (getClass().getGenericSuperclass() instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
            Type[] types = parameterizedType.getActualTypeArguments();
            if (types.length > 0) {
                Class classz = (Class) types[0];
                try {
                    return (B) classz.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class)
                            .invoke(null, inflater, container, false);
                } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
